package com.pulsar.handler;

import com.pulsar.message.ResponseCode;
import com.pulsar.message.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 功能描述: <br>
 * 所属包名: com.pulsar.handler<br>
 * 创建人　: 白剑<br>
 * 创建时间: 07/15/2018 17:29 Sunday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@ControllerAdvice // 作为一个controller与前台交互
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class) // 可以细化异常
    @ResponseBody
    public Result<String> exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {

        e.printStackTrace();

        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getRc());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(ResponseCode.BIND_ERROR.fillArgs(msg));
        } else {
            return Result.error(ResponseCode.SERVER_ERROR);
        }

    }
}
